import uuid

from flask import Blueprint
from flask_restful import Api, Resource, reqparse

from apps.models.user import User
from exts import cache

user_bp = Blueprint('user', __name__)
api = Api(user_bp)

login_parser = reqparse.RequestParser()
login_parser.add_argument('username', location='form')
login_parser.add_argument('password', location='form')


class UserAPI(Resource):
    def post(self):
        args = login_parser.parse_args()
        username = args.get('username')
        password = args.get('password')
        users = User.query.filter(User.username == username)
        if users:
            for user in users:
                if user.password == password:
                    token = str(uuid.uuid4()).replace('-', '')
                    cache.set(token, username)
                    return {"token": token}
        else:
            return {"msg": "不存在该用户", "status": 400}


api.add_resource(UserAPI, '/login')